Page({
  data: {
    categoryList: [],
    productList: [],
    currentCategoryIndex: 0 
  },
  onLoad() {
    this.loadData();
  },
  async loadData() {
    try {
      const category = '示例分类值'; 
      const cateRes = await this.getCategories(category);
      this.setData({
        categoryList: cateRes.data.data
      });

      const productRes = await this.productListRequest();
      this.setData({
        productList: productRes.data.data
      });
    } catch (error) {
      console.error('数据获取失败：', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  getCategories(category) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://47.94.6.186:3001/api/pro/categorylist',
        method: 'GET',
        data: { category },
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  productListRequest(count = 1, limitNum = 20) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://47.94.6.186:3001/api/pro/list',
        method: 'GET',
        data: { count, limitNum },
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  handleCategoryClick(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentCategoryIndex: index
    });

    const selectedCategory = this.data.categoryList[index];
    this.loadProductsByCategory(selectedCategory);
  },

  async loadProductsByCategory(category) {
    try {
      const productRes = await this.productListRequest();
      this.setData({
        productList: productRes.data.data
      });
    } catch (error) {
      console.error('分类商品获取失败：', error);
    }
  },

  goToDetail(e) {
    const proid = e.currentTarget.dataset.proid;
    wx.navigateTo({
      url: `/pages/detail/detail?proid=${proid}`,
    });
  }
});
